package it.storm.solution;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 59. 螺旋矩阵 II
 * https://leetcode-cn.com/problems/spiral-matrix-ii/
 */
public class Solutions_59 {
    public static void main(String[] args) {
        int n1 = 3;  // output: {{1, 2, 3}, {8, 9, 4}, {7, 6, 5}}
        int n2 = 1;  // output: {{1}}

        List<Integer> inputs = new ArrayList<>();
        inputs.add(n1);
        inputs.add(n2);

        for (int input : inputs) {
            int[][] result = generateMatrix(input);
            System.out.println(Arrays.deepToString(result));
        }
    }

    /**
     * 与 54 题解法一致
     */
    public static int[][] generateMatrix(int n) {
        int up = 0, down = n - 1;
        int left = 0, right = n - 1;
        int num = 1;
        int[][] res = new int[n][n];

        while (true) {
            // 上
            for (int i = left; i <= right; i++) {
                res[up][i] = num ++;
            }
            up ++;
            if (up > down) {
                break;
            }
            // 右
            for (int i = up; i <= down; i++) {
                res[i][right] = num ++;
            }
            right --;
            if (right < left) {
                break;
            }
            // 下
            for (int i = right; i >= left; i--) {
                res[down][i] = num ++;
            }
            down --;
            if (down < up) {
                break;
            }
            // 左
            for (int i = down; i >= up; i--) {
                res[i][left] = num ++;
            }
            left ++;
            if (left > right) {
                break;
            }
        }
        return res;
    }
}
